package com.slz3.business.module.configManagement.conShareManage.steward;

import com.slz3.business.frame.steward.FindJoinSteward;
import com.slz3.business.frame.util.LocalDT;
import com.slz3.business.frame.util.VE;
import com.slz3.business.module.configManagement.conShareManage.domain.ConShareManage;
import com.slz3.business.module.configManagement.conShareManage.domain.ConShareManageCondition;
import com.slz3.business.module.configManagement.conShareManage.domain.ConShareManageFactory;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.MultiValueMap;

import javax.persistence.criteria.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class ConShareManageSpecification {

    public static FindJoin findJoin(MultiValueMap<String, String> params) {
        return new FindJoin(params);
    }

    private static class FindJoin implements Specification<ConShareManage> {

        private MultiValueMap<String, String> params;

        private ConShareManageCondition condition;

        public FindJoin(MultiValueMap<String, String> params) {
            this.params = params;
            this.condition = ConShareManageFactory.newConShareManageCondition(params);
        }

        @Override
        public Predicate toPredicate(Root<ConShareManage> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

            try {

                final List<Predicate> predicateList = new ArrayList<>();

                predicateList.addAll(FindJoinSteward.appoint(root, cb, ConShareManage.class, params));

                if (VE.isNotEmpty(condition.getCreateTimeOUTSET()))
                    predicateList.add(cb.greaterThanOrEqualTo(root.get("createTime"), condition.getCreateTimeOUTSET()));

                if (VE.isNotEmpty(condition.getCreateTimeFINISH()))
                    predicateList.add(cb.lessThanOrEqualTo(root.get("createTime"), condition.getCreateTimeFINISH()));

                if (VE.isNotEmpty(condition.getLastModifyTimeOUTSET()))
                    predicateList.add(cb.greaterThanOrEqualTo(root.get("lastModifyTime"), condition.getLastModifyTimeOUTSET()));

                if (VE.isNotEmpty(condition.getLastModifyTimeFINISH()))
                    predicateList.add(cb.lessThanOrEqualTo(root.get("lastModifyTime"), condition.getLastModifyTimeFINISH()));

                if (VE.isNotEmpty(condition.getSerAuditList())) {
                    CriteriaBuilder.In in = cb.in(root.get("serAudit"));
                    condition.getSerAuditList().forEach(item -> in.value(item));
                    predicateList.add(in);
                }

                return predicateList.size() > 0 ? cb.and(predicateList.toArray(new Predicate[]{})) : null;

            } catch (Exception e) {

                e.printStackTrace();

                return cb.and(cb.equal(root.get("uuid"), "0"));

            }

        }

    }

}
